<template>
  <div class="injureReport">
    <div class="injureReport-header noprint">
      <el-card class="drug-head-contatiner-title2" shadow="never">
        <h2>医务室（医疗点）工作信息日报表</h2>
        <el-form
          :inline="true"
          :model="formSearch"
          ref="searchDialogRef"
          class="demo-form-inline"
          :rules="reportMedicalPointFormRulesMixin.searchFormRules"
        >
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formSearch.startTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formSearch.endTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="所属城市" prop="citycode">
            <el-tree-select
              v-model="formSearch.citycode"
              :data="cityTreeOption"
              :props="defaultProps"
              node-key="Code"
              :check-strictly="true"
              :render-after-expand="false"
              clearable
              filterable
            />
          </el-form-item>
          <el-form-item label="场馆">
            <el-select
              v-model="formSearch.activityvenuescode"
              placeholder="--选择--"
              multiple
              collapse-tags
              collapse-tags-tooltip
              clearable
              filterable
            >
              <el-option
                v-for="item in activityVenuesOption"
                :key="item.Code"
                :label="item.CHIDescription"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="医疗点" prop="medicalPoint">
            <el-select
              v-model="formSearch.medicalPoint"
              placeholder="--选择--"
              clearable
              filterable
              ref="venuesRef"
            >
              <el-option
                v-for="item in medicalPointOption"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="是否测试" prop="isTest">
            <el-select
              v-model="formSearch.isTest"
              placeholder="--选择--"
              clearable
              filterable
            >
              <el-option :key="1" label="是" :value="1" />
              <el-option :key="0" label="否" :value="0" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button type="primary" @click="onlyPrint">打印</el-button>
            <el-dropdown @command="handleCommand" style="margin: 10px">
              <el-button type="primary">
                导出<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="a">Excel</el-dropdown-item>
                  <el-dropdown-item command="b">pdf</el-dropdown-item>
                  <el-dropdown-item command="c">Word</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="injureReport-list" v-loading="loading">
      <iframe
        src=""
        frameborder="0"
        id="print-iframe"
        tabindex="-1"
        style="
          border: none;
          cursor: inherit;
          height: calc(100vh - 300px);
          width: 100%;
          opacity: 1;
          transition: opacity 200ms linear;
          transition-delay: 100ms;
          marginwidth: 0;
          marginheight: 0;
          allowtransparency: yes;
        "
        title="预览窗格"
        aria-live="polite"
        aria-atomic="true"
      ></iframe>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, toRaw, watch } from 'vue';
import { reportMedicalPointFormRulesMixin } from '@/utils/mixin';
import { ElMessage } from 'element-plus';
import store from '@/store';
import { Base64 } from 'js-base64';
import { getInjuryStatistics1 } from '@/network/report';
import lodash from 'lodash';
import {
  getActivityVenues,
  getCityTree,
  getMedicPointDicNormal,
} from '@/network/dictionary.js';
const venuesRef = ref(null);
const cityTreeOption = ref([]);
const activityVenuesOption = ref([]);
const searchDialogRef = ref(null);
let medicalPointOptionArray = [];
let venuesOptionArray = [];
const defaultProps = {
  children: 'Children',
  label: 'Name',
  value: 'Code',
};
const loading = ref(true);
const onSubmit = async () => {
  loading.value = true;
  initData();
};
const medicalPointOption = ref([]);
const handleCommand = (command) => {
  console.info(command);
  switch (command) {
    case 'a':
      // lodash.debounce(csaa(), 300, {
      //   leading: true,
      //   trailing: false,
      // });
      exportFile('医务室（医疗点）工作信息日报表.xlsx');
      break;
    case 'b':
      exportFile('医务室（医疗点）工作信息日报表.pdf');
      break;
    case 'c':
      exportFile('医务室（医疗点）工作信息日报表.docx');
      break;
    default:
      break;
  }
};
const exportFile = async (filename) => {
  console.info('调用了！');
  let paramsPrint = {
    startTime: formSearch.startTime,
    endTime: formSearch.endTime,
    citycode: formSearch.citycode,
    activityvenuescode: formSearch.activityvenuescode?.toString(),
    filename,
    ifDevide: false,
    fillPerson: formSearch.fillPerson,
    medicalPoint: formSearch.medicalPoint,
    telephone: formSearch.telephone,
    medicalPointName: venuesRef.value.selectedLabel,
    isTest: formSearch.isTest,
  };
  await getInjuryStatistics1(paramsPrint, 'blob').then((ret) => {
    let bytearray = Base64.toUint8Array(ret.data.FileContents);
    let blob = new Blob([bytearray]);
    const link = document.createElement('a'); //利用a标签自定义下载文件名
    link.style.display = 'none';
    //设置连接
    link.href = URL.createObjectURL(blob);
    link.download = filename; //自定义文件名字
    document.body.appendChild(link);
    // 模拟点击事件;
    link.click();
    link.parentNode.removeChild(link);
    URL.revokeObjectURL(link.href);
  });
};
const initDic = async () => {
  await getCityTree().then((res) => {
    cityTreeOption.value = res;
  });
  await getActivityVenues().then((res) => {
    activityVenuesOption.value = res;
    venuesOptionArray = res;
  });
  await getMedicPointDicNormal().then((res) => {
    medicalPointOption.value = res;
    medicalPointOptionArray = res;
    // formSearch.medicalPoint = res[0].Code;
  });
  formSearch.fillPerson = JSON.parse(store.state.app.userInfo).Name;

  formSearch.telephone = JSON.parse(store.state.app.userInfo).Telephone;
  //监听watch
  watch(
    [() => formSearch.citycode, () => formSearch.activityvenuescode],
    (newValue, oldValue) => {
      // 城市变更--场馆变更--车辆变更--理疗店变更
      if (newValue[0] != oldValue[0]) {
        if (!newValue[0] || newValue[0] == 1) {
          activityVenuesOption.value = venuesOptionArray;
          medicalPointOption.value = medicalPointOptionArray;
        } else {
          formSearch.activityvenuescode = null;
          formSearch.medicalPoint = null;
          //车辆和医疗点、场馆都重新赋值
          activityVenuesOption.value = venuesOptionArray.filter(
            (it) => it.CityCode == newValue[0],
          );
          medicalPointOption.value = medicalPointOptionArray.filter(
            (it) => it.CityCode == newValue[0],
          );
        }
      }
      // 场馆变更   城市不变   车辆、医疗点变
      if (newValue[1] != oldValue[1]) {
        if (!newValue[1]) {
          if (newValue[0] && newValue[0] != 1) {
            medicalPointOption.value = medicalPointOptionArray.filter(
              (it) => it.CityCode == newValue[0],
            );
          } else {
            //医疗点重置
            medicalPointOption.value = medicalPointOptionArray;
          }
        } else {
          formSearch.medicalPoint = null;
          medicalPointOption.value = medicalPointOptionArray.filter(
            (it) =>
              toRaw(newValue[1]) &&
              Array.from(toRaw(newValue[1])).includes(it.VenuesCode),
          );
        }
      }
    },
    {
      deep: true,
    },
  );
  initData();
};
const initData = async () => {
  searchDialogRef.value.validate(async (valid) => {
    if (valid) {
      //初始化受伤统计1
      let datasearch = {
        startTime: formSearch.startTime,
        endTime: formSearch.endTime,
        citycode: formSearch.citycode,
        activityvenuescode: formSearch.activityvenuescode?.toString(),
        filename: 'cs.html',
        ifDevide: formSearch.ifDevide,
        fillPerson: formSearch.fillPerson,
        medicalPointName: venuesRef.value.selectedLabel,
        telephone: formSearch.telephone,
        medicalPoint: formSearch.medicalPoint,
        isTest: formSearch.isTest,
      };
      // formSearch.medicalPoint = venuesRef.value.selectedLabel;
      await getInjuryStatistics1(datasearch).then((res) => {
        loading.value = false;
        let bytearray = Base64.decode(res.data.FileContents);
        //判断iframe是否存在，不存在则创建iframe
        var iframe = document.getElementById('print-iframe');
        var doc = null;
        doc = iframe.contentWindow.document;
        //这里可以自定义样式
        //doc.write("<LINK rel="stylesheet" type="text/css" href="css/print.css">");
        doc.write('<div>' + bytearray + '</div>');
        doc.close();
        iframe.contentWindow.focus();
      });
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
onMounted(() => {
  initDic();
});
const formSearch = reactive({
  startTime: getInitTime(),
  endTime: getInitTime(0, ' 23:59:59'),
  activityvenuescode: '',
  citycode: '',
  fillPerson: '',
  medicalPoint: null,
  telephone: '',
  isTest: 0,
});

function getInitTime(intday, hour) {
  let secodenpast = new Date().getTime() - (intday || 0) * 24 * 60 * 60 * 1000;
  var now = new Date(secodenpast);
  var year = now.getFullYear(); //得到年份
  var month = now.getMonth(); //得到月份
  var date = now.getDate(); //得到日期
  hour = hour || ' 00:00:00'; //默认时分秒 如果传给后台的格式为年月日时分秒，就需要加这个，如若不需要，此行可忽略
  month = month + 1;
  month = month.toString().padStart(2, '0');
  date = date.toString().padStart(2, '0');
  let x = `${year}-${month}-${date}${hour}`;
  return x;
}
const onReset = () => {
  formSearch.startTime = getInitTime();
  formSearch.endTime = getInitTime(0, ' 23:59:59');
  formSearch.activityvenuescode = '';
  formSearch.citycode = '';
  formSearch.isTest = null;
  formSearch.medicalPoint = null;
};
const onlyPrint = () => {
  // window.print();
  var iframe = document.getElementById('print-iframe');
  iframe.contentWindow.print();
};
</script>
<style lang="scss" scoped>
.injureReport {
  margin: 14px 15px 14px;
  .injureReport-header {
    .drug-head-contatiner-title2 {
      h2 {
        text-align: center;
        margin-bottom: 14px;
      }
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
}
</style>
